/**
 * 接口权限页面逻辑
 *
 * @版权所有 rem.studio
 */
import React, { PureComponent, Fragment } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  message,
  Divider,
  Radio,
  Popconfirm,
  Checkbox,
  Icon,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { saveAs } from 'file-saver';
import ProTable from '@ant-design/pro-table';

import styles from './Admin.less';

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const InputGroup = Input.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  return (
    <Modal
      destroyOnClose
      title={formatMessage({ id: 'app.sysurl.add-url' })}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 19 }}
        label={formatMessage({ id: 'app.sysurl.url' })}
      >
        {form.getFieldDecorator('url', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.url.required' }),
            },
            {
              message: formatMessage({ id: 'validation.url.length' }),
              max: 512,
            },
          ],
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 19 }}
        label={formatMessage({ id: 'app.sysurl.description' })}
      >
        {form.getFieldDecorator('description', {
          rules: [
            {
              message: formatMessage({ id: 'validation.description.length' }),
              max: 256,
            },
          ],
        })(<Input.TextArea placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
    </Modal>
  );
});

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => {},
    handleUpdateModalVisible: () => {},
    values: {},
  };

  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        url: props.values.url,
        description: props.values.description,
        id: props.values.id,
      },
    };

    this.formLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 19 },
    };
  }

  renderContent = formVals => {
    const { form } = this.props;

    return [
      <FormItem key="url" {...this.formLayout} label={formatMessage({ id: 'app.sysurl.url' })}>
        {form.getFieldDecorator('url', {
          rules: [
            {
              required: true,
            },
          ],
          initialValue: formVals.url,
        })(<Input disabled placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
      <FormItem
        key="description"
        {...this.formLayout}
        label={formatMessage({ id: 'app.sysurl.description' })}
      >
        {form.getFieldDecorator('description', {
          rules: [
            {
              message: formatMessage({ id: 'validation.description.length' }),
              max: 256,
            },
          ],
          initialValue: formVals.description,
        })(<Input.TextArea placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
    const { formVals } = this.state;
    const okUpdateHandle = () => {
      const { form, handleUpdate } = this.props;
      const { formVals: oldValue } = this.state;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...oldValue, ...fieldsValue };
        this.setState(
          {
            formVals,
          },
          () => {
            handleUpdate(formVals);
          }
        );
      });
    };

    return (
      <Modal
        destroyOnClose
        title={formatMessage({ id: 'app.sysurl.edit-url' })}
        visible={updateModalVisible}
        onOk={okUpdateHandle}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
      >
        {this.renderContent(formVals)}
      </Modal>
    );
  }
}

@Form.create()
class AuthorizeForm extends PureComponent {
  static defaultProps = {
    handleAuthorize: () => {},
    handleAuthorizeModalVisible: () => {},
    values: {},
  };

  state = {
    checkedKeys: this.props.checkedKeys,
    indeterminate: true,
    checkAll: false,
  };

  onChange = checkedKeys => {
    this.setState({
      checkedKeys,
      indeterminate: !!checkedKeys.length && checkedKeys.length < this.props.checkedKeys.length,
      checkAll: checkedKeys.length === this.props.checkedKeys.length,
    });
  };

  onCheckAllChange = e => {
    var roleDataValue = [];
    this.props.roleData.map(function(item) {
      roleDataValue.push(item['value']);
    });
    this.setState({
      checkedKeys: e.target.checked ? roleDataValue : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };

  render() {
    const {
      authorizeModalVisible,
      handleAuthorizeModalVisible,
      handleAuthorize,
      values,
      roleData,
    } = this.props;
    const okAuthorizeHandle = () => {
      handleAuthorize(values.id, this.state.checkedKeys);
    };

    return (
      <Modal
        destroyOnClose
        title={formatMessage({ id: 'app.common.authorize' })}
        visible={authorizeModalVisible}
        onOk={okAuthorizeHandle}
        onCancel={() => handleAuthorizeModalVisible(false, values)}
        afterClose={() => handleAuthorizeModalVisible()}
      >
        <div className={styles.checkboxall}>
          <Checkbox
            indeterminate={this.state.indeterminate}
            onChange={this.onCheckAllChange}
            checked={this.state.checkAll}
          >
            全选
          </Checkbox>
        </div>
        <br />
        <Checkbox.Group
          style={{ width: '100%' }}
          options={roleData}
          value={this.state.checkedKeys}
          onChange={this.onChange}
        />
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ sysUrl, loading }) => ({
  sysUrl,
  loading: loading.models.sysUrl,
}))
@Form.create()
class SysUrl extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    authorizeModalVisible: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    roleData: {},
    checkedKeys: [],
    hiddenMenuButton: localStorage.getItem('cancersystem_menubutton'),
  };

  columns = [
    {
      title: formatMessage({ id: 'app.sysurl.url' }),
      copyable: true,
      ellipsis: true,
      dataIndex: 'url',
      width: 400,
    },
    {
      title: formatMessage({ id: 'app.sysurl.description' }),
      dataIndex: 'description',
    },
    {
      title: formatMessage({ id: 'app.common.create-time' }),
      dataIndex: 'createTime',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      width: '200px',
      render: (text, record) => (
        <Fragment>
          {this.state.hiddenMenuButton.indexOf('sysurl:update') !== -1 ? null : (
            <a onClick={() => this.handleUpdateModalVisible(true, record)}>
              <Icon type="edit" />
              {formatMessage({ id: 'app.common.edit' })}
            </a>
          )}
          <Divider type="vertical" />
          <a onClick={() => this.handleAuthorizeFetch(record)}>
            <Icon type="safety-certificate" />
            {formatMessage({ id: 'app.common.authorize' })}
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={formatMessage({ id: 'app.common.confirm-delete' })}
            onConfirm={() => this.deleteItem(record.id)}
          >
            {this.state.hiddenMenuButton.indexOf('sysurl:delete') !== -1 ? null : (
              <a>
                <Icon type="delete" />
                {formatMessage({ id: 'app.common.delete' })}
              </a>
            )}
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUrl/fetch',
    });
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'sysUrl/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'sysUrl/fetch',
      payload: {},
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUrl/delete',
      payload: {
        id: id,
      },
    }).then(response => {
      if (response.message == 'success') {
        this.setState({
          selectedRows: [],
        });
        message.success(formatMessage({ id: 'app.common.delete-success' }));
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUrl/fetch',
        payload: {},
      });
    });
  };

  handleDeleteClick = () => {
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) {
      message.warning(formatMessage({ id: 'app.common.choose-delete' }));
      return;
    }

    Modal.confirm({
      title: formatMessage({ id: 'app.common.batch-delete' }),
      content: formatMessage({ id: 'app.common.confirm-batch-delete' }),
      okText: formatMessage({ id: 'app.common.confirm' }),
      cancelText: formatMessage({ id: 'app.common.cancel' }),
      onOk: () => this.deleteItem(selectedRows.map(row => row.id)),
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    if (e) {
      e.preventDefault();
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'sysUrl/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {},
    });
  };

  handleAuthorizeFetch = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUrl/fetchCheckbox',
    });
    dispatch({
      type: 'sysUrl/fetchCheckedRole',
      payload: {
        urlId: record.id,
      },
    }).then(response => {
      this.handleAuthorizeModalVisible(true, record);
    });
  };

  handleAuthorizeModalVisible = (flag, record) => {
    this.setState({
      authorizeModalVisible: !!flag,
      updateFormValues: record || {},
    });
  };

  handleExport = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'sysUrl/export',
        payload: values,
      }).then(response => {
        saveAs(response, formatMessage({ id: 'app.sysurl.url-manage' }) + '.xlsx');
        dispatch({
          type: 'sysUrl/fetch',
          payload: values,
        });
      });
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUrl/add',
      payload: {
        url: fields.url,
        description: fields.description,
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.add-success' }));
        this.handleModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUrl/fetch',
        payload: {},
      });
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUrl/update',
      payload: {
        body: {
          url: fields.url,
          description: fields.description,
          id: fields.id,
        },
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.edit-success' }));
        this.handleUpdateModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUrl/fetch',
        payload: {},
      });
    });
  };

  handleAuthorize = (urlId, checkedKeys) => {
    if (checkedKeys.length === 0) {
      message.warning(formatMessage({ id: 'validation.url-role.required' }));
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUrl/authorize',
      payload: {
        urlId: urlId,
        roleId: checkedKeys,
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.authorize-success' }));
        this.handleAuthorizeModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUrl/fetch',
        payload: {},
      });
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysurl.url' })}>
              {getFieldDecorator('url')(
                <Input placeholder={formatMessage({ id: 'app.common.enter' })} />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type="primary"
                icon="reload"
              >
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      sysUrl: { data, checkboxData, checkedRoleData },
      loading,
    } = this.props;
    const {
      /**selectedRows,**/ modalVisible,
      updateModalVisible,
      updateFormValues,
      authorizeModalVisible,
    } = this.state;
    let roleData;
    if ({ checkboxData }.checkboxData) {
      roleData = { checkboxData }.checkboxData;
    }
    let checkedKeys;
    if ({ checkedRoleData }.checkedRoleData) {
      checkedKeys = { checkedRoleData }.checkedRoleData;
    }
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const authorizeMethods = {
      handleAuthorizeModalVisible: this.handleAuthorizeModalVisible,
      handleAuthorize: this.handleAuthorize,
    };
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.handleSelectRows(selectedRows);
      },
    };
    return (
      <div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              {this.state.hiddenMenuButton.indexOf('sysurl:add') !== -1 ? null : (
                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                  {formatMessage({ id: 'app.common.add' })}
                </Button>
              )}
              {this.state.hiddenMenuButton.indexOf('sysurl:export') !== -1 ? null : (
                <Button icon="file-excel" type="primary" onClick={this.handleExport}>
                  {formatMessage({ id: 'app.common.export' })}
                </Button>
              )}
              {this.state.hiddenMenuButton.indexOf('sysurl:delete') !== -1 ? null : (
                <Button icon="delete" type="danger" ghost onClick={this.handleDeleteClick}>
                  {formatMessage({ id: 'app.common.batch-delete' })}
                </Button>
              )}
            </div>
            <ProTable
              bordered={true}
              search={false}
              rowKey={record => record.id}
              rowSelection={rowSelection}
              loading={loading}
              dataSource={data ? data.list : []}
              pagination={data ? data.pagination : {}}
              columns={this.columns}
              onChange={this.handleBasicTableChange}
              options={{
                density: true,
                reload: () => {
                  this.handleSearch();
                },
                fullScreen: true,
                setting: true,
              }}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
        {updateFormValues && Object.keys(updateFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
          />
        ) : null}
        {updateFormValues && Object.keys(updateFormValues).length ? (
          <AuthorizeForm
            {...authorizeMethods}
            authorizeModalVisible={authorizeModalVisible}
            roleData={roleData}
            checkedKeys={checkedKeys}
            values={updateFormValues}
          />
        ) : null}
      </div>
    );
  }
}

export default SysUrl;
